//
//  LZXAppDelegate.m
//  LocalRecorderDemo
//
//  Created by x on 13-7-25.
//  Copyright (c) 2013年 . All rights reserved.
//

#import "ThumbnailImageForRecord.h"

@implementation ThumbnailImageForRecord

@synthesize ParentID;

@synthesize directoryPath;
@synthesize dataSource;
//@synthesize cameraUID;

@synthesize thumbnailImageArr;

- (id)init
{
    if (self = [super init])
    {
        isRun = YES;
        [self readyInit];
    }
    return self;
}


- (void)thumbnailImageForRecordStart {
    isRun = YES;
    NSLog(@"thumbnailImageForRecordStart; isRun = YES");
    
    dispatch_queue_t thumbnailImageForRecordQueue = dispatch_queue_create("thumbnailImageForRecord", NULL);
    dispatch_async(thumbnailImageForRecordQueue, ^{
        [self toGetThumbnailImageArr];
    });
}

- (void)thumbnailImageForRecordStop {
    NSLog(@"thumbnailImageForRecordStop; isRun = NO");
    isRun = NO;
}

- (void)thumbnailImageForRecordDestroy {
}

// 获取视频的缩略图
- (void)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLock *aLock = [NSLock new];
    [aLock lock];
    
    NSLog(@"thumbnailImageForVideo, videoURL=%@", videoURL);
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSLog(@"thumbnailImageForVideo, 1");
    NSParameterAssert(asset);
    NSLog(@"thumbnailImageForVideo, 2");
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    NSLog(@"thumbnailImageForVideo, 3");
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    NSLog(@"thumbnailImageForVideo, 3.1");
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    NSLog(@"thumbnailImageForVideo, 3.2");
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 1) actualTime:NULL error:&thumbnailImageGenerationError];
    NSLog(@"thumbnailImageForVideo, 4");
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *image = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : [[UIImage alloc] init];
    NSLog(@"thumbnailImageForVideo, 5");
    
    NSLog(@"image.size.width=%f, image.size.height=%f", image.size.width, image.size.height);
    NSData *dataObj = UIImageJPEGRepresentation(image, 1.0);
    NSLog(@"thumbnailImageArr dataObj.length=%d", dataObj.length);
    
    [self.thumbnailImageArr addObject:image];
    
    NSLog(@"=====  thumbnailImageArr.count=%d\n", self.thumbnailImageArr.count);
    
    [image release];
    CGImageRelease(thumbnailImageRef);
    [assetImageGenerator release];
    [asset release];
    
    [aLock unlock];
    [aLock release];
    [pool release];
}

/*
 - (NSArray *)dataSource {
	if (!dataSource) {
 
 NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
 FMResultSet *rs = [database executeQuery:@"SELECT * FROM record WHERE dev_uid=?", cameraUID];
 
 while([rs next]) {
 
 NSString *filePath = [rs stringForColumn:@"file_path"];
 NSLog(@"DB-record-file_path:%@", filePath);
 [mutableArray addObject:[NSString stringWithFormat:@"%@", filePath]];
 }
 [rs close];
 dataSource = [[NSArray alloc] initWithArray:mutableArray];
 [mutableArray release];
 }
 
	return dataSource;
 }
 */


- (void)toGetThumbnailImageArr {
    //for clearing all image
    //[thumbnailImageArr removeAllObjects];
    
    printf("=========== toGetThumbnailImageArr self.dataSource.count=%d\n",
           self.dataSource.count);
    
    int i;
    for (i=0; i<self.dataSource.count; i++) {
        
        if (!isRun) {
            break;
        }
        
        [self thumbnailImageForVideo:[NSURL fileURLWithPath:[self.directoryPath stringByAppendingPathComponent:[self.dataSource objectAtIndex:i]]] atTime:1];
        
        printf("=========== toGetThumbnailImageArr toThumbnailImageArr, i=%d, thumbnailImageArr.count=%d\n", i, self.thumbnailImageArr.count);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.ParentID && [self.ParentID respondsToSelector:@selector(thumbnailImageCompleted)])
                [self.ParentID thumbnailImageCompleted];
        });
    }
    
}

- (void)readyInit
{
    self.thumbnailImageArr = [[NSMutableArray alloc] init];
}


- (void)dealloc {
    [self.directoryPath release];
    [self.thumbnailImageArr removeAllObjects];
    [self.thumbnailImageArr release];
    [self.dataSource release];
    //[self.cameraUID release];
    [super dealloc];
}

@end
